#!/usr/bin/python3
# coding:utf-8

import rospy
import os
import numpy as np
from std_msgs.msg import Int32
import time
import shutil
from attach_download import AttDown
class Host_A:
    def __init__(self):
        rospy.init_node('Host_A', anonymous=True)
        self.rate = rospy.Rate(0.1)
        self.pkg_path = rospy.get_param("/host_a/pkg_path")
        self.file_path = rospy.get_param("/host_a/file_path")
        self.file_path = os.path.join(self.pkg_path,self.file_path)
        self.u_path = rospy.get_param("/host_a/u_path")
        
        self.att_down = AttDown(self.file_path)
        self.global_status = 0

        rospy.Subscriber("/global_status", Int32, self.cb_global_status)
        self.status_publish = rospy.Publisher("/host_a_status", Int32, queue_size=1)

    def cb_global_status(self,data):
        self.global_status = data.data
        if self.global_status == 1:
            while not os.path.exists(self.u_path):
                pass
            file_list = self.att_down.get_file_list()
            self.att_down.empty_file_list()
            for file in file_list:
                if os.path.exists(os.path.join(self.u_path,file)):
                    pass
                shutil.move(os.path.join(self.file_path,file), self.u_path)
            self.status_publish.publish(1)
            self.global_status = 0

    def MainLoop(self):
        while not rospy.is_shutdown():
            self.att_down.update_email()
            self.rate.sleep()


if __name__ == '__main__':
    node1 = Host_A()
    node1.MainLoop()

